package com.cmuis.goodguide;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This activity displays the results of a GoodGuide search. All searches are
 * directed to this page. Creates a view for each item in the list.
 * 
 * @author Stephanie
 * 
 */
public class resultspage extends Activity {

	/**
	 * Displays a list in which each row of the list is a product. Each product
	 * can be clicked which directs the user to the DetailsPage.java file, which
	 * allows them to view more details and ratings for the product.
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Checks if the activity is connected to the network.
		final Context activity = this;
		ConnectivityManager cMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		boolean connected = (cMgr.getActiveNetworkInfo() != null
				&& cMgr.getActiveNetworkInfo().isAvailable() && cMgr
				.getActiveNetworkInfo().isConnected());
		// returns an alert if there is no connection available
		if (!connected) {
			Log.e("error", "No connection available ");
			AlertDialog.Builder downloadDialog = new AlertDialog.Builder(this);
			downloadDialog.setTitle("No Connection Found");
			downloadDialog
					.setMessage("You are not connected to any data services, please reconnect and try again");
			downloadDialog.setNeutralButton("Close",
					new DialogInterface.OnClickListener() {
						// in the case of no network, on closing the alert, the
						// user is directed to the home page
						public void onClick(DialogInterface dialogInterface,
								int i) {
							Intent redirect = new Intent(activity,
									goodguide.class);
							startActivity(redirect);
						}
					});
			downloadDialog.show();
		} else {// if network connection is established

			setContentView(R.layout.resultsview);
			final TextView text = (TextView) findViewById(R.id.results_text);

			Intent intent = getIntent();
			String query = "";
			// if the user decides to conduct another search, save the query the
			// user uses, and also conduct the search for the query.
			if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
				query = intent.getStringExtra(SearchManager.QUERY);
				SearchRecentSuggestions suggestions = new SearchRecentSuggestions(
						this, ContentProvider.AUTHORITY, ContentProvider.MODE);
				suggestions.saveRecentQuery(query, null);
			} else {// save the previous query the user searched for
				Bundle b = intent.getExtras();
				query = b.getString("query");
			}

			final List<Product> products = this.openConnection(query);

			List<HashMap<String, Object>> displayList = new ArrayList<HashMap<String, Object>>();
			if (products == null || products.isEmpty()) {
				text.setText("No Results Found. Please try another search");
			}
			else
			{
			Iterator<Product> iter = products.iterator();

			/**
			 * Converts the List of Products into a Hashmap where the keys
			 * reference a column to be displayed in the results page, and where
			 * the value references a value in the column.
			 */
			while (iter.hasNext()) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				Product p = iter.next();
				map.put("product", p.getName().toString());
				if (p.getRating("root") == null)
				{
				map.put("rating", "-");
				}
				else {
					map.put("rating", p.getRating("root").toString());
					if (p.getRating("root").startsWith("-") == false) {
						Double rating = Double.parseDouble(p.getRating("root"));
						if (rating < 2) {
							map.put("img", R.drawable.lowest_rating);
						}
						if (rating >= 2 && rating < 4) {
							map.put("img", R.drawable.low_rating);
						}
						if (rating >= 4 && rating < 6) {
							map.put("img", R.drawable.mid_rating);
						}
						if (rating >= 6 && rating < 8) {
							map.put("img", R.drawable.mid_high_rating);
						}
						if (rating >= 8 && rating <= 10) {
							map.put("img", R.drawable.high_rating);
						}
					} else {
						map.put("img", R.drawable.no_rating);
					}

				displayList.add(map);
			}
			}
			ListView list = (ListView) findViewById(R.id.results_view);

			// Displays the products with two columns: product and ID as a
			// clickable
			SimpleAdapter mSchedule = new SimpleAdapter(resultspage.this,
					displayList, R.layout.rows, new String[] { "product", "rating", "img"},
					new int[] { R.id.product_name,  R.id.list_ratings, R.id.rating_image });
			
			
			
			list.setAdapter(mSchedule);
			// allows users to press a letter and filter results
			list.setTextFilterEnabled(true);
			list.setOnItemClickListener(new OnItemClickListener() {
				@Override
				// sets the details view when an item is clicked in the list.
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Intent itemIntent = new Intent(view.getContext(),
							DetailsPage.class);
					Bundle b = new Bundle();
					// gives the id and upc of the product to the next Activity
					b.putString("productID", products.get(position).getId()
							.toString());
					b.putString("UPC", null);
					itemIntent.putExtras(b);
					startActivity(itemIntent);
				}
			});
		}
		}
	}

	/**
	 * Receives a search query from a user, parses the resulting XML file into a
	 * list of ProductList objects.
	 */
	protected List<Product> openConnection(String name) {
		try {
			URL url;
			name = name.replace(' ', '+');
			url = new URL(
					"http://api.goodguide.com/"
							+ "search.xml?api_key=chm22jq6d5f5ytnnnfwan726&api_version=1.0&"
							+ "&api_format=simple&q=" + name
							+ "&sort_by=best_match");

			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();

			XMLReader xr = sp.getXMLReader();

			ProductListParser handler = new ProductListParser();
			xr.setContentHandler(handler);

			xr.parse(new InputSource(url.openStream()));

			return handler.getProducts();

		} catch (Exception e) {
			return null;
		}

	}

	/**
	 * Creates the standard menu in android applications. (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu, menu);
		return true;
	}

	/**
	 * Sets the menu options in the standard android menu for each main activity
	 * in the application.
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {

		case R.id.search:
			// checks if internet is connected
			ConnectivityManager cMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			boolean connected = (cMgr.getActiveNetworkInfo() != null
					&& cMgr.getActiveNetworkInfo().isAvailable() && cMgr
					.getActiveNetworkInfo().isConnected());

			if (connected) {
				// if connected, start search activity
				Intent i = new Intent(this, goodguide.class);
				startActivity(i);
			} else {// else, create an alert stating that no connection is
					// found.
				Log.e("error", "No connection available ");
				AlertDialog.Builder downloadDialog = new AlertDialog.Builder(
						this);
				downloadDialog.setTitle("No Connection Found");
				downloadDialog
						.setMessage("You are not connected to any data services, please reconnect and try again");
				downloadDialog.setNeutralButton("Close",
						new DialogInterface.OnClickListener() {
							// allows user to close the notification
							public void onClick(
									DialogInterface dialogInterface, int i) {
								return;
							}
						});
				downloadDialog.show();
			}
			return true;
		case R.id.barcode_scanner:
			Intent j = new Intent(this, barcodescanner.class);
			startActivity(j);
			return true;
		case R.id.history:
			Intent p = new Intent(this, History.class);
			startActivity(p);
			return true;
		case R.id.info:
			Intent q = new Intent(this, InfoPage.class);
			startActivity(q);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

}